import { Col, message, Modal, Row, Form } from "antd";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { DragDropContext, DropResult } from "react-beautiful-dnd";
import { request, RoomStatus, request_func } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { DraggableOlderElements, DroppableBedElements, RoomStatusWrapElements } from "src/projects/components/room-status-style";
import { Bed, HotelZone } from "src/projects/models/hotel_zone";
import { BedStatuss } from "./bedStatus";
import { RoomChangeView } from "../room-change/change-room";

const { confirm } = Modal;

/**
 * 组件：房态图视图状态
 */
export interface RoomStatusViewState extends ReactViewState {
    roomStatusElement: RoomStatus[];
    bedInfo?: Bed;
    upperElement?: HotelZone[];
    /** 调房弹框状态 */
    roomstatus?: boolean;
    /**
     * TODO: 人员没有接口对应，所以先返回any
     */
    residentInfo?: any;
    /**
     * 颜色池
     */
    colorPool?: string[];
    /** 显示弹框_退住 */
    visible_retreat?: boolean;
    /** 用户id */
    user_id?: string;
    /** 调床位，当前所在床位id */
    bed_id?: string;
    /** 调床位，调整后的床位id */
    destination_bed_id?: string;
}

/**
 * 组件：房态图视图
 * 描述
 */
export class RoomStatusView extends ReactView<RoomStatusViewControl, RoomStatusViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            roomStatusElement: [],
            roomstatus: false,
            bedInfo: undefined,
            upperElement: [],
            user_id: '',
            bed_id: '',
            destination_bed_id: '',
            colorPool: ["rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)", "rgba(41, 186, 254, 0.08)"],
            visible_retreat: false
        };
    }

    componentDidMount() {
        this.getRoomStatus({});
    }

    /**
     * 通过接口获取房态图信息
     */
    getRoomStatus(condition?: {}) {
        request(this, AppServiceUtility.hotel_zone_service!.get_room_status_list!(condition))
            .then((datas: any) => {
                let roomStatusInstance = new RoomStatus();
                // 排序，按照顶级元素数量排序，顶级元素排在前头
                (datas.result as RoomStatus[]).sort((a, b) =>
                    a.upper_element.length - b.upper_element.length
                );
                this.setState({
                    roomStatusElement: roomStatusInstance.buildOrAddElements!(datas.result)!
                });
            });
    }

    /**
     * 获取床位位置
     */
    getBedPosition(id: string) {
        request(this, AppServiceUtility.hotel_zone_type_service!.get_bed_position!({ id: id }))
            .then((datas: any) => {
                this.setState({
                    upperElement: datas.result[0].upper_element
                });
            });
    }

    /**
     * 获取长者信息
     * @param id 床位id
     */
    getResidentInfo(id: string) {
        request(this, AppServiceUtility.hotel_zone_type_service!.get_residents_of_bed!({ id: id }))
            .then((datas: any) => {
                console.warn(datas.result[0].user[0]);
                this.setState({
                    residentInfo: datas.result[0].user[0]
                });
            });
    }

    /**
     * 获取床位详细信息
     */
    getBedInfo(id: string) {
        request(this, AppServiceUtility.hotel_zone_type_service!.get_bed_list!({ id: id }))
            .then((datas: any) => {
                this.setState({
                    bedInfo: datas.result[0]
                });
            });
    }

    /**
     * 床位信息、床位位置、床位相关长者信息获取
     */
    getAllInfo(id: string) {
        this.getBedInfo(id);
        this.getBedPosition(id);
        this.getResidentInfo(id);
    }

    /**
     * 获取床位视图渲染元素
     */
    getBedEle(bed: Bed[], user: any[]) {
        // 数据库出来的user字段与bed字段的顺序不是一一对应的，只能这样寻找床位对应的长者
        function getResidentsOfBed(bed: Bed) {
            for (let iUser = 0; iUser < user.length; iUser++) {
                const eUser = user[iUser];
                if (bed.residents_id === eUser.id) {
                    return eUser;
                }
            }
            return undefined;
        }

        return bed.map((e, i) => {
            const userOfBed = getResidentsOfBed(e);
            return (
                // 可拖拽元素
                <div key={i} onClick={() => this.getAllInfo(e.id)} className={userOfBed ? "bed" : 'none_user_bed'}>
                    {e.name}
                    {
                        // 因为长者数组长度一定不会超过床位长度，所以可以这么判断是否需要增加长者元素
                        userOfBed ?
                            <DraggableOlderElements
                                residentsId={userOfBed.id}
                                residentsName={userOfBed.name}
                                index={i}
                            />
                            :
                            undefined
                    }
                </div>
            );
        });
    }

    /**
     * 拖拽结束回调函数
     */
    onDragEnd = (result: DropResult) => {
        console.log(result);
        // dropped outside the list
        if (!result.destination) {
            return;
        }

        const that = this;
        console.log(that);
        function showConfirm() {
            confirm({
                title: '警告',
                content: '是否换床位？',
                // TODO: 确定取消文本可以用区域取代
                okText: "确定",
                cancelText: "取消",
                onOk() {
                    that.setState({
                        roomstatus: true,
                        user_id: result.draggableId,
                        bed_id: result.source!.droppableId,
                        destination_bed_id: result.destination!.droppableId
                    });
                    // AppServiceUtility.accommodation_process_service!.change_room_process!({ "user_id": result.draggableId, "new_bed_id": result.destination!.droppableId })!.then((data: any) => {
                    //     if (data === "Success") {
                    //         message.info("床位调换成功");
                    //         that.getRoomStatus();
                    //     }
                    // });
                },
                onCancel() {

                },
            });
        }

        if (result.source.droppableId === result.destination.droppableId) {
            // 相同床位就不做处理
            return;
        } else {
            showConfirm();
        }
    }

    /**
     * 递归生成房态图节点
     * @param level 房态图
     */
    traversalRoomStatusAndGetHtml(roomStatusElement: RoomStatus[], level: number): any {
        let currentEle = roomStatusElement;
        const levelNow = level;
        // 遍历当前节点
        return currentEle.map((roomStatus, i) => {
            // console.log('roomStatus>>', roomStatus);
            let childEle;
            let bedEle: JSX.Element[];

            if (roomStatus.down_element.length > 0) {
                // 当前节点有下级元素，则遍历子节点
                childEle = this.traversalRoomStatusAndGetHtml(roomStatus.down_element, levelNow + 1);

            }

            // 无下级元素，目前来看，则一定有床位元素
            if (roomStatus.bed && roomStatus.bed.length > 0) {
                bedEle = this.getBedEle(roomStatus.bed, roomStatus.user!);
            }

            // 返回当前节点生成的元素
            return (
                <RoomStatusWrapElements key={i} roomStatus={roomStatus} colorPool={this.state.colorPool!} level={levelNow} >
                    {
                        childEle ?
                            childEle.map((e: any, i: number) =>
                                (
                                    <Col key={i}>
                                        {e}
                                    </Col>
                                )
                            )
                            :
                            bedEle! ?
                                <Row type={"flex"}>
                                    {
                                        bedEle!.map((e: any, i: number) =>
                                            (
                                                <DroppableBedElements
                                                    key={i}
                                                    bedId={roomStatus.bed![i].id}
                                                    bedJSXElement={e}
                                                />
                                            )
                                        )
                                    }
                                </Row>
                                :
                                undefined
                    }
                </RoomStatusWrapElements>
            );
        });
    }

    /** 退住 */
    retreat = () => {
        this.setState({
            visible_retreat: true
        });
    }
    /** 调用退住方法 */
    check_out = () => {
        // 退住接口
        request_func(this, AppServiceUtility.accommodation_process_service.check_out_process, [this.state.bedInfo!['residents_id']], (data: any) => {
            if (data === 'Success') {
                message.info('退住成功！');
            } else {
                message.info(data);
            }
            this.setState({
                visible_retreat: false
            });
            this.getRoomStatus({});
        });
    }

    handleclose() {
        this.setState({
            roomstatus: false
        });
    }
    render() {
        let { roomStatusElement, bedInfo, upperElement, residentInfo } = this.state;
        const bedStatusButton = [
            {
                name: '全部',
                color: 'white',
                click_back: () => { this.getRoomStatus({}); },
            },
            {
                name: '空床',
                color: 'white',
                click_back: () => { this.getRoomStatus({ is_none_user: 'one' }); },
            },
            {
                name: '单人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 1 }); },
            },
            {
                name: '双人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 2 }); },
            },
            {
                name: '三人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 3 }); },
            },
            {
                name: '四人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 4 }); },
            },
            {
                name: '五人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 5 }); },
            },
            {
                name: '六人房',
                color: 'white',
                click_back: () => { this.getRoomStatus({ room_type: 6 }); },
            },
        ];
        return (
            (
                <DragDropContext onDragEnd={this.onDragEnd}>
                    <Row type={"flex"} className="room-status-display">
                        <Col span={20}>
                            {this.traversalRoomStatusAndGetHtml(roomStatusElement, 0)}
                        </Col>
                        <Col span={4}>
                            <BedStatuss
                                bed_status_arr={bedStatusButton}
                                bed_status_info={bedInfo!}
                                bed_position_info={upperElement!}
                                resident_info={residentInfo}
                                retreat={this.retreat}
                            />
                            <Modal
                                title="床位调整"
                                visible={this.state.roomstatus}
                                onCancel={this.handleclose = this.handleclose.bind(this)}
                                footer={false}
                                width={1000}
                                destroyOnClose={true}
                            >
                                <Row>
                                    {/* <Col span={12}>
                                        <h5>旧房间信息</h5>
                                        <RoomChangeView key={'old'} user_id={this.state.user_id} bed_id={this.state.bed_id} form={this.props.form} />
                                    </Col> */}
                                    <Col span={24}>
                                        <h5>新房间信息</h5>
                                        <RoomChangeView
                                            key={'new'}
                                            user_id={this.state.user_id}
                                            bed_id={this.state.destination_bed_id}
                                            form={this.props.form}
                                            back_fuc={() => { this.setState({ roomstatus: false }); this.getRoomStatus({}); }}
                                        />
                                    </Col>
                                </Row>
                            </Modal>
                        </Col>
                    </Row>
                    <Modal title="退住操作" visible={this.state.visible_retreat} onOk={this.check_out} okText="确定" onCancel={() => this.setState({ visible_retreat: false })} cancelText="取消" destroyOnClose={true} width={'400px'}>
                        <p>是否要退住该长者:</p>
                        <p>长者名称：{this.state.bedInfo ? this.state.bedInfo!['residents'] : ''}</p>
                        <p>房间：{this.state.bedInfo ? this.state.bedInfo!['area_name'] : ''}</p>
                        <p>床位：{this.state.bedInfo ? this.state.bedInfo!['name'] : ''}</p>
                    </Modal>
                </DragDropContext>
            )
        );
    }
}

/**
 * 控件：房态图视图控制器
 * 描述
 */
@addon('RoomStatusView', '房态图', '房态图')
@reactControl(Form.create<any>()(RoomStatusView), true)
export class RoomStatusViewControl extends ReactViewControl {
    /** 请求接口名 */
    public request_url?: string;
    /** 获取权限接口类 */
    public permission_class?: any;
    /** 获取权限接口方法名 */
    public get_permission_name?: string;
    /** 查询权限 */
    public select_permission?: string;
    /** 编辑权限 */
    public edit_permission?: string;
    /** 删除权限 */
    public delete_permission?: string;
    /** 新增权限 */
    public add_permission?: string;
}